package com.damai.action.aop.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import com.citywithincity.api.ApiConfig;
import com.citywithincity.utils.CachedClassUtil;
import com.damai.action.aop.Invoker;
import com.damai.action.aop.controller.Controller;

public class ControllerInvoker implements Invoker {

	private Class<? extends Controller> controllerClass;
	private Method method;
	
	public ControllerInvoker(Class<? extends Controller> controllerClass,Method method) {
		this.controllerClass = controllerClass;
		this.method = method;
	}
	
	
	@Override
	public Object invoke(HttpServletRequest request, Object[] args) {
		Object controller = CachedClassUtil.newController(controllerClass);
		
		try {
			return method.invoke(controller, args);
		}catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			Throwable throwable = e.getTargetException();
			ApiConfig.error(throwable);
			if(throwable instanceof RuntimeException){
				throw (RuntimeException)throwable;
			}
			throw new RuntimeException(throwable);
		}
	}

}
